package com.yoho.vpm.custom

import android.content.Context
import android.graphics.*
import android.support.v4.widget.TextViewCompat
import android.support.v7.widget.AppCompatTextView
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.TextView
import com.yoho.vpm.R
import io.reactivex.Observable
import java.util.concurrent.TimeUnit

/**
 * Created by xz on 2018/1/26.
 */
class SkipButtonView : TextView, View.OnClickListener {

    private var hasClick: Boolean = false

    private var onMyClickListener: OnMyClickListener? = null
    // 圆实心的颜色
    private var circleSolidColor: Int = 0

    // 圆边框的颜色
    private var circleStrokeColor: Int = 0

    private var defaultStrokeWidth: Float = 4f
    private var progressWidth: Float = 4f

    private var progressColor: Int = 0

    private var progress = 100

    private var circleRadius: Int = 0

    private var text_color: Int = 0

    private var mPaint = Paint()

    private var mText = "跳过"

    private var mRect = Rect()

    private var listener: OnProgressListener? = null

    //跳过等待时间
    private val timeMillis: Long = 3000

    private var mArcRectF = RectF()

    private var mProgressType = ProgressType.COUNT

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        var typeArray = context.obtainStyledAttributes(attrs, R.styleable.SkipButtonView)
        circleSolidColor = typeArray.getColor(R.styleable.SkipButtonView_circleSolidColor, Color.parseColor("#FF0000"))
        circleStrokeColor = typeArray.getColor(R.styleable.SkipButtonView_circleStrokeColor, Color.parseColor("#666666"))
        defaultStrokeWidth = typeArray.getDimension(R.styleable.SkipButtonView_circleStrokeWidth, defaultStrokeWidth)
        progressColor = typeArray.getColor(R.styleable.SkipButtonView_progressColor, Color.BLUE)
        text_color = typeArray.getColor(R.styleable.SkipButtonView_textColor, Color.WHITE)
        typeArray.recycle()
        init()
        start()
    }
    private fun init() = setOnClickListener(this)
    /**
     * 进度条类型(方便做一个扩展，这里默认的是倒数进度条)
     */
    enum class ProgressType {
        /**
         * 顺数进度条，从0-100；
         */
        COUNT,

        /**
         * 倒数进度条，从100-0；
         */
        COUNT_BACK
    }

    /**
     * 设置布局的高宽相等 并设置半径长度
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var height = measuredHeight
        var width = measuredWidth
        if (height > width) {
            height = width
        } else {
            width = height
        }
        circleRadius = width / 2
        setMeasuredDimension(width, height)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        //画实心圆
        getDrawingRect(mRect)
        mPaint.isAntiAlias = true
        mPaint.style = Paint.Style.FILL
        mPaint.color = circleSolidColor
        canvas?.drawCircle(mRect.centerX().toFloat(), mRect.centerY().toFloat(), circleRadius.toFloat(), mPaint)

        //画边框
        mPaint.color = circleStrokeColor
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = defaultStrokeWidth
        canvas?.drawCircle(mRect.centerX().toFloat(), mRect.centerY().toFloat(), circleRadius.toFloat() - defaultStrokeWidth + 1, mPaint)

        //画 文字
        var textPaint = paint
        textPaint.color = text_color
        textPaint.textAlign = Paint.Align.CENTER
        val textY = mRect.centerX() - (textPaint.descent() + textPaint.ascent()) / 2
        canvas?.drawText(mText, mRect.centerX().toFloat(), textY, textPaint)


        //画进度条
        mPaint.color = progressColor
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = progressWidth
        mPaint.strokeCap = Paint.Cap.ROUND

        mArcRectF.set(mRect.left + progressWidth, mRect.top + progressWidth, mRect.right - progressWidth, mRect.bottom - progressWidth)
        canvas?.drawArc(mArcRectF, -90f, 360f * progress / 100, false, mPaint)
    }

    fun setText(text: String) {
        mText = text
    }

    private fun drawTask() {

        Observable.intervalRange(1, 3, 1, 1, TimeUnit.SECONDS)

    }


    /**
     * 验证进度。
     * @param progress 你要验证的进度值。
     * @return 返回真正的进度值。
     */
    private fun validateProgress(progress: Int): Int {
        var progress = progress
        if (progress > 100)
            progress = 100
        else if (progress < 0)
            progress = 0
        return progress
    }


    /**
     * 进度更新task
     */
    private val progressChangeTask = object : Runnable {
        override fun run() {
            removeCallbacks(this)
            when (mProgressType) {
                ProgressType.COUNT -> progress += 1
                ProgressType.COUNT_BACK -> progress -= 1
            }
            if (progress in 0..100) {

                invalidate()
                postDelayed(this, timeMillis / 60)
                Log.d("aaa", progress.toString())
            } else {
                progress = validateProgress(progress)
                if (listener != null && !hasClick) {
                    listener!!.onSuccess()
                }
            }
        }
    }


    /**
     * 开始。
     */
    fun start() {
        resetProgress()
        post(progressChangeTask)
    }

    fun stop() {
        removeCallbacks(progressChangeTask)
    }

    /**
     * 重置进度。
     */
    private fun resetProgress() {
        progress = when (mProgressType) {
            ProgressType.COUNT -> 0
            ProgressType.COUNT_BACK -> 100
        }
    }


    fun setOnMyClickListener(onMyClickListener: OnMyClickListener) {
        this.onMyClickListener = onMyClickListener
    }

    interface OnMyClickListener {
        fun onClick()
    }

    override fun onClick(v: View?) {
        hasClick = true
        stop()
        onMyClickListener?.onClick()
    }

    //点击||完成回调
    interface OnProgressListener {
        fun onSuccess()
    }

    fun setOnProgressListener(listener: OnProgressListener) {
        this.listener = listener
    }

}